package com.jack.network;

import android.app.Application;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkRequest;
import android.os.Build;

/**
 * @author: dingfeng
 * @date: 2020-04-12
 * @since: 1.0.0
 **/
public class NetworkManager {

    private static volatile NetworkManager instance;

    private Application mApplication;

    private INetWorkMonitor mNetWorkMonitor;

    private NetworkManager() {
        mNetWorkMonitor = new NetWorkMonitorImpl();
    }

    public static NetworkManager getDefault() {
        if (instance == null) {
            synchronized (NetworkManager.class) {
                if (instance == null) {
                    instance = new NetworkManager();
                }
            }
        }
        return instance;
    }

    public Application getApplication() {
        if (mApplication == null)
            throw new RuntimeException("Please init first.");
        return mApplication;
    }

    public void init(Application application) {
        this.mApplication = application;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            NetworkCallbackImpl networkCallback = new NetworkCallbackImpl();
            NetworkRequest.Builder builder = new NetworkRequest.Builder();
            NetworkRequest request = builder.build();
            ConnectivityManager connectivityManager = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    connectivityManager.registerDefaultNetworkCallback(networkCallback);
                } else {
                    connectivityManager.registerNetworkCallback(request, networkCallback);
                }
                networkCallback.setNetWorkMonitor(mNetWorkMonitor);
            }
        } else {
            NetworkStateReceiver receiver = new NetworkStateReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            application.registerReceiver(receiver, filter);

            receiver.setNetWorkMonitor(mNetWorkMonitor);
        }
    }

    public void registerObserver(Object observer) {
        if (mNetWorkMonitor != null)
            mNetWorkMonitor.registerObserver(observer);
    }

    public void unRegisterObserver(Object observer) {
        if (mNetWorkMonitor != null)
            mNetWorkMonitor.unRegisterObserver(observer);
    }

    public void unRegisterAllObservers() {
        if (mNetWorkMonitor != null)
            mNetWorkMonitor.unRegisterAllObservers();
    }

}
